//
//  LocationManageViewController.m
//  MeterMart
//
//  Created by ENERGY on 2018/9/25.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "LocationManageViewController.h"
#import "LocationManageTableViewCell.h"
#import "AddAddressViewController.h"
#import "ConfirmOrderViewController.h"
#import "WeChatLoginViewController.h"

@interface LocationManageViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)NSMutableArray * cellArr;
@property (nonatomic, strong)UIViewController * lastVC;//push过来的控制器
@property (nonatomic, strong)NSString * addressID;//地址ID
@property (nonatomic, strong)NSString * phoneString;
@property (nonatomic, strong)NSString * tokenString;
- (void)ifLogin;
@end

@implementation LocationManageViewController(networking)
//地址列表
- (void)getUserAddressData{
    NSDictionary * dic = @{
                           @"phone":self.phoneString,
                           @"token":self.tokenString,
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"usiosApi/address" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            [self.cellArr removeAllObjects];
            [self.cellArr addObjectsFromArray:responseObject[@"list"][@"address"]];
            [self.tableView reloadData];
        }else if ([[NSString stringWithFormat:@"%@", responseObject[@"sign"]] isEqualToString:@"400"]) {
            [self ifLogin];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}
//更改默认地址
- (void)changeDefaultAddressWithIndexPath:(int)row{
    NSDictionary * dic = @{
                           @"id":self.addressID,
                           @"phone":self.phoneString,
                           @"token":self.tokenString,
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"usiosApi/statusUpdate" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            //把所有行的status状态都改为0
            for (int i = 0; i<self.cellArr.count; i++) {
                NSMutableDictionary * singleDic = [NSMutableDictionary dictionaryWithDictionary:self.cellArr[i]];
                [singleDic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                    if ([key isEqualToString:@"status"]) {
                        [singleDic setObject:@"0" forKey:@"status"];
                    }
                }];
                [self.cellArr replaceObjectAtIndex:i withObject:singleDic];
            }
            //把所点击的行的status状态修改为1
            NSMutableDictionary * cellDic = [NSMutableDictionary dictionaryWithDictionary:self.cellArr[row]];
            [cellDic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                if ([key isEqualToString:@"status"]) {
                    [cellDic setObject:@"1" forKey:@"status"];
                }
            }];
            [self.cellArr replaceObjectAtIndex:row withObject:cellDic];
            [self.tableView reloadData];
        }else if ([[NSString stringWithFormat:@"%@", responseObject[@"sign"]] isEqualToString:@"400"]) {
            [self ifLogin];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self hiddenProgressHUD];
    }];
}
//删除地址
- (void)deleteAddress{
    NSDictionary * dic = @{
                           @"phone":self.phoneString,
                           @"token":self.tokenString,
                           @"receiveid":self.addressID
                           };
    [[AFAppDotNetAPIClient sharedClient] POST:@"usiosApi/deleteaddress" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            [self getUserAddressData];//获取地址列表
        }else if ([[NSString stringWithFormat:@"%@", responseObject[@"sign"]] isEqualToString:@"400"]) {
            [self ifLogin];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
    }];
}
@end
@implementation LocationManageViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    if ([[UserModel sharedInstanced].token isEqualToString:@""] || [UserModel sharedInstanced].token == nil || [[UserModel sharedInstanced].token length] == 0 || [[UserModel sharedInstanced].mobile isEqualToString:@""] || [UserModel sharedInstanced].mobile == nil || [[UserModel sharedInstanced].mobile length] == 0) {
        self.tokenString = @"";
        self.phoneString = @"";
    }else{
        self.tokenString = [UserModel sharedInstanced].token;
        self.phoneString = [UserModel sharedInstanced].mobile;
    }
    [self getUserAddressData];//网络接口
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"地址管理";
    self.view.backgroundColor = [UIColor whiteColor];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    //右侧按钮
    UIButton * addAddressBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30/WIDTH_6_SCALE, 30/WIDTH_6_SCALE)];
    [addAddressBtn setTitle:@"添加" forState:UIControlStateNormal];
    [addAddressBtn addTarget:self action:@selector(addAddressBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [addAddressBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    addAddressBtn.titleLabel.font = DEF_FontSize_14;
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithCustomView:addAddressBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    //左侧按钮
    UIButton * backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30/WIDTH_6_SCALE, 30/WIDTH_6_SCALE)];
    [backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    [self.view addSubview:self.tableView];
}
#pragma mark - init
- (NSMutableArray *)cellArr{
    if (!_cellArr) {
        _cellArr = @[].mutableCopy;
    }return _cellArr;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVI_HEIGHT - BOTTOM_HEIGHT) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = 137/WIDTH_6_SCALE;
        [_tableView registerClass:[LocationManageTableViewCell class] forCellReuseIdentifier:NSStringFromClass([LocationManageTableViewCell class])];
        _tableView.backgroundColor = getColor(mainColor);
    }return _tableView;
}
#pragma mark - tableViewDelegate和tableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LocationManageTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LocationManageTableViewCell class]) forIndexPath:indexPath];
    cell.model = self.cellArr[indexPath.row];
    __weak typeof (self)weakSelf = self;
    cell.defaultBtnSetBlock = ^(NSString * _Nonnull addressID) {
        weakSelf.addressID = addressID;
        [self changeDefaultAddressWithIndexPath:(int)indexPath.row];
    };
    cell.deleteBtnBlock = ^(NSString * _Nonnull addressID) {
        weakSelf.addressID = addressID;
        [self deleteAddress];
    };
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.cellArr.count;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    __weak typeof (self)weakSelf = self;
    NSArray *vcsArray = [self.navigationController viewControllers];
    NSInteger vcCount = vcsArray.count;
    self.lastVC = vcsArray[vcCount-2];
    if ([self.lastVC isKindOfClass:[ConfirmOrderViewController class]]) {
        if (self.takeAddressIDBlock) {
            [self.navigationController popViewControllerAnimated:YES];
            self.takeAddressIDBlock([weakSelf.cellArr[indexPath.row] objectForKey:@"receiveid"], @"LocationManageViewController");
        }
    }else{
        NSLog(@"我的页跳入");
    }
}
#pragma mark - action
- (void)addAddressBtnClick:(UIButton *)sender{
    AddAddressViewController * vc = [[AddAddressViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)backBtnClick:(UIButton *)sender{
    __weak typeof (self)weakSelf = self;
    NSArray *vcsArray = [self.navigationController viewControllers];
    NSInteger vcCount = vcsArray.count;
    self.lastVC = vcsArray[vcCount-2];
    if ([self.lastVC isKindOfClass:[ConfirmOrderViewController class]]) {
        if (self.takeAddressIDBlock) {
            [self.navigationController popViewControllerAnimated:YES];
            if (weakSelf.cellArr.count > 1) {
                self.takeAddressIDBlock(weakSelf.addressContentID, @"LocationManageViewController");
            }else if(weakSelf.cellArr.count == 0){
                self.takeAddressIDBlock(@"0", @"LocationManageViewController");
            }else if (weakSelf.cellArr.count == 1){
                //遍历数组，查找默认的地址，返回带回去
                for (int i = 0; i<weakSelf.cellArr.count; i++) {
                    if ([[weakSelf.cellArr[i] objectForKey:@"status"] isEqualToString:@"1"]) {
                        self.takeAddressIDBlock([weakSelf.cellArr[i] objectForKey:@"receiveid"], @"LocationManageViewController");
                    }
                }
            }
        }
    }else{
        NSLog(@"我的页跳入");
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)ifLogin{
    WeChatLoginViewController * vc = [[WeChatLoginViewController alloc] init];
    UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:vc];
    vc.backHomePageBlock = ^{
        [vc dismissViewControllerAnimated:YES completion:nil];
        [self.tabBarController setSelectedIndex:0];
        [self.navigationController popToRootViewControllerAnimated:YES];
    };
    [self presentViewController:navi animated:YES completion:nil];
}
@end
